const csv = require("csv");
const fs = require("fs");
const path = require("path");


/**
 * @returns {Promise<{records:Any}>}
 * @param {String} data 
 */
function csv_parse(data) {
  return new Promise(resolve => {
    csv.parse(data, {}, (err, records) => {
      if (err) {
        debugger
        return;
      }
      resolve({
        records: records
      })
    })
  })
}

/**
 * @returns {Promise<string>}
 * @param {String} file_path 
 */
function read(file_path) {
  return new Promise(resolve => {
    fs.readFile(file_path, (err, data) => {
      if (err) {
        debugger
        return;
      }
      resolve(data.toString());
    })
  })
}


(async () => {
  let d_read = await read(path.join(__dirname, "./mc1-reports-data.csv"));
  let o_parse = await csv_parse(d_read);
  let o_parse_0 = o_parse.records[0];//是表头
  let last_records = [];
  for (let i = 1; i < o_parse.records.length; i++) {
    let d = o_parse.records[i];
    let time_text = d[0];
    let sewer_and_water = d[1].length ? Number(d[1]) : null;
    let power = d[2].length ? Number(d[2]) : null;
    let roads_and_bridges = d[3].length ? Number(d[3]) : null;
    let medical = d[4].length ? Number(d[4]) : null;
    let buildings = d[5].length ? Number(d[5]) : null;
    let shake_intensity = d[6].length ? Number(d[6]) : null;
    let location = Number(d[7]);
    last_records.push({
      time_text: time_text,
      time_stamp: (new Date(time_text)).valueOf(),
      sewer_and_water: sewer_and_water,
      power: power,
      roads_and_bridges: roads_and_bridges,
      medical: medical,
      buildings: buildings,
      shake_intensity: shake_intensity,
      location: location
    })
  }
  let min_timestamp = Infinity;
  let max_timestamp = -Infinity;
  for (let o of last_records) {
    if (min_timestamp > o['time_stamp']) {
      min_timestamp = o['time_stamp']
    }
    if (max_timestamp < o['time_stamp']) {
      max_timestamp = o['time_stamp']
    }
  }
  debugger
  last_records = last_records.sort((a,b)=>{
    return a.time_stamp - b.time_stamp
  })
  let json_str = JSON.stringify({ records: last_records, min_timestamp, max_timestamp })


  fs.writeFile(path.join(__dirname, "./raw-to-timeline.json"), json_str, (err) => {
    debugger
  })

  // debugger
})();